package com.book.core.exception.handler;

import com.book.core.enums.REnum;
import com.book.core.exception.BookReturnException;
import com.book.core.exception.BorrowBookException;
import com.book.core.exception.FileUpException;
import com.book.core.exception.ReaderException;
import com.book.core.mode.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.ConnectException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;

/**
 * 全局异常处理器
 *
 * @author hongmizfb
 * @date 2025/05/10
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalHandler {
    @ExceptionHandler(value = BorrowBookException.class)
    public R BorrowBookExceptionHandler(BorrowBookException e) {
        return R.err(e.getMessage());
    }

    @ExceptionHandler(value = ReaderException.class)
    public R ReaderExceptionHandler(ReaderException e) {
        return R.err(e.getMessage());
    }

    @ExceptionHandler(value = BookReturnException.class)
    public R BookReturnExceptionHandler(BookReturnException e) {
        e.printStackTrace();
        return R.err(e.getMessage());
    }

    @ExceptionHandler(value = SQLSyntaxErrorException.class)
    public R SQLSyntaxErrorExceptionHandler(SQLSyntaxErrorException e) {
        e.printStackTrace();
        return R.err("数据库异常!");
    }

    @ExceptionHandler(value = IOException.class)
    public R IOExceptionHandler(IOException e) {
        e.printStackTrace();
        return R.err("读写失败!");
    }

    @ExceptionHandler(value = FileUpException.class)
    public R FileUpExceptionHandler(FileUpException e) {
        return R.err(e.getMessage());
    }

    /**
     * 校验异常
     *
     * @param e
     * @return {@link R }
     */
    @ExceptionHandler(BindException.class)
    public R validatedBindException(BindException e) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return R.err(message);
    }

    //    服务器连接异常
    @ExceptionHandler(value = ConnectException.class)
    public R ConnectExceptionHandler(ConnectException e) {
        e.printStackTrace();
        log.error("服务器连接异常,请查看redis是否启动？");
        return R.err(REnum.CONNECT_ERROR);
    }
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R SQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException e) {
        e.printStackTrace();
        log.error("数据库完整性异常，请查看数据库字段约束");
        return R.err("操作失败！");
    }
}
